package com.dianxin.smartpark.service.access.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.IdUtil;
import com.chinatelecom.response.common.CommonResponseBody;
import com.chinatelecom.response.utils.BeanUtil;
import com.chinatelecom.response.utils.ResponseBodyWrapperUtil;
import com.chinatelecom.response.utils.StringUtils;
import com.dianxin.acl.api.acl.AclFileRpcService;
import com.dianxin.acl.api.acl.AclUserRpcService;
import com.dianxin.acl.api.dto.SsoUserDTO;
import com.dianxin.acl.api.dto.SysFileDTO;
import com.dianxin.acl.api.qo.SsoUserRpcQO;
import com.dianxin.common.oss.properties.FileUploadResponse;
import com.dianxin.common.oss.util.MinioUtil;
import com.dianxin.smartpark.api.cons.PassPersonType;
import com.dianxin.smartpark.dao.dataobject.access.SmartParkAccessControlPassRecord;
import com.dianxin.smartpark.dao.dataobject.access.SmartParkAccessControlPassRecordExampleExt;
import com.dianxin.smartpark.dao.mapper.access.SmartParkAccessControlPassRecordMapper;
import com.dianxin.smartpark.dao.qo.access.SmartParkAccessControlPassRecordQO;
import com.dianxin.smartpark.dao.qo.attendance.SmartParkAttendanceRecordQO;
import com.dianxin.smartpark.dao.qo.visitor.SmartParkVisitorQO;
import com.dianxin.smartpark.service.access.SmartParkAccessControlPassRecordService;
import com.dianxin.smartpark.service.attendance.SmartParkAttendanceGroupService;
import com.dianxin.smartpark.service.attendance.SmartParkAttendanceRecordService;
import com.dianxin.smartpark.service.visitor.SmartParkVisitorService;
import com.dianxin.smartpark.service.vo.access.SmartParkAccessControlPassRecordVO;
import com.dianxin.smartpark.service.vo.visitor.SmartParkVisitorVO;
import io.netty.util.internal.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author wangkai
 */
@Service
public class SmartParkAccessControlPassRecordServiceImpl implements SmartParkAccessControlPassRecordService {
    private final static Logger logger = LoggerFactory.getLogger(SmartParkAccessControlPassRecordServiceImpl.class);
    @Resource
    private SmartParkAccessControlPassRecordMapper smartParkAccessControlPassRecordMapper;
    @Resource
    private MinioUtil minioUtil;

    @Resource
    private AclUserRpcService aclUserRpcService;

    @Resource
    private AclFileRpcService aclFileRpcService;

    @Resource
    private SmartParkVisitorService smartParkVisitorService;

    @Resource
    private SmartParkAttendanceRecordService saveAttendanceRecord;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public CommonResponseBody<Boolean> savePassRecord(SmartParkAccessControlPassRecordVO vo) {
        // 验证 todo
        SmartParkAccessControlPassRecord smartParkAccessControlPassRecord = new SmartParkAccessControlPassRecord();


        try {

            BeanUtil.insertConversion(vo, smartParkAccessControlPassRecord);
            if (vo.getUserId() != null && PassPersonType.EMPLOYEE.getPersonTypeCode().equals(vo.getPassPersonType())) {
                SsoUserRpcQO ssoUserRpcQO = new SsoUserRpcQO();
                ssoUserRpcQO.setUserId(String.valueOf(vo.getUserId()));
                CommonResponseBody<SsoUserDTO> user = aclUserRpcService.getUser(ssoUserRpcQO);
                if (user.getData() != null) {
                    smartParkAccessControlPassRecord.setPassPersonIdNum(user.getData().getIdCard());
                    smartParkAccessControlPassRecord.setPassPersonPhoneNum(user.getData().getPhone());
                    smartParkAccessControlPassRecord.setPassPersonName(user.getData().getRealName());
                }

            } else {
                SmartParkVisitorQO smartParkVisitorQO = new SmartParkVisitorQO();
                smartParkVisitorQO.setId(vo.getUserId());
                CommonResponseBody<SmartParkVisitorVO> voCommonResponseBody = smartParkVisitorService.selectSmartParkVisitor(smartParkVisitorQO);
                if (voCommonResponseBody.isSuccess() && voCommonResponseBody.getData() != null) {
                    smartParkAccessControlPassRecord.setPassPersonIdNum(voCommonResponseBody.getData().getVisitorIdNum());
                    smartParkAccessControlPassRecord.setPassPersonPhoneNum(voCommonResponseBody.getData().getVisitorPhoneNum());
                    smartParkAccessControlPassRecord.setPassPersonName(voCommonResponseBody.getData().getVisitorName());
                }

            }
            smartParkAccessControlPassRecord.setCreator(vo.getUserId() + "");
            smartParkAccessControlPassRecord.setModifier(vo.getUserId() + "");
            //上传照片
            if (StringUtils.isNotNull(vo.getScreenshot())) {
                String filename = IdUtil.objectId() + ".png" ;
                BASE64Decoder decoder = new BASE64Decoder();
                byte[] b = decoder.decodeBuffer(vo.getScreenshot().replace("data:image/jpg;base64,", ""));
                FileUploadResponse visitorPhotoUploadResponse = minioUtil.uploadFile(b, "access-pass-photo", filename);

                SysFileDTO sysFileDTO = new SysFileDTO();
                sysFileDTO.setBusiType(3);
                sysFileDTO.setFilePath(filename);
                sysFileDTO.setFileName(filename);
                sysFileDTO.setFileUrl(visitorPhotoUploadResponse.getUrlHttp());
                sysFileDTO.setFileExt("png");
                sysFileDTO.setTenantId(vo.getTenantId());
                sysFileDTO.setBucketName("access-pass-photo");
                CommonResponseBody<SysFileDTO> dtoCommonResponseBody1 = aclFileRpcService.insertSysFile(sysFileDTO);
                if (!dtoCommonResponseBody1.isSuccess()) {
                    return ResponseBodyWrapperUtil.fail("文件插入失败", "400");
                }

                sysFileDTO = dtoCommonResponseBody1.getData();
                if (StringUtils.isNull(sysFileDTO)) {
                    return ResponseBodyWrapperUtil.fail("文件插入失败", "400");
                }
                smartParkAccessControlPassRecord.setScreenshot(Convert.toStr(sysFileDTO.getId()));
            }
        } catch (Exception e) {
            smartParkAccessControlPassRecord.setScreenshot(null);
            logger.error("", e);
        }
        smartParkAccessControlPassRecordMapper.insert(smartParkAccessControlPassRecord);
        SmartParkAttendanceRecordQO smartParkAttendanceRecordQO = new SmartParkAttendanceRecordQO();
        smartParkAttendanceRecordQO.setTenantId(smartParkAccessControlPassRecord.getTenantId());
        smartParkAttendanceRecordQO.setUserId(smartParkAccessControlPassRecord.getCreator()!=null?Long.valueOf(smartParkAccessControlPassRecord.getCreator()):null);
        smartParkAttendanceRecordQO.setUserName(smartParkAccessControlPassRecord.getPassPersonName());
        SsoUserRpcQO qo = new SsoUserRpcQO();
        qo.setUserId(smartParkAccessControlPassRecord.getCreator());
        CommonResponseBody<SsoUserRpcQO> userDetail = aclUserRpcService.getUserDetail(qo);
        if(userDetail.getData()!=null&&userDetail.getData().getDeptList().size()>0){
            smartParkAttendanceRecordQO.setDeptId(userDetail.getData().getDeptList().get(0).getId());
            smartParkAttendanceRecordQO.setDeptName(userDetail.getData().getDeptList().get(0).getDeptName());
        }
        smartParkAttendanceRecordQO.setClockInTime(smartParkAccessControlPassRecord.getPassTime());
        smartParkAttendanceRecordQO.setClockInSource(Long.valueOf(smartParkAccessControlPassRecord.getDeviceCode()));
        smartParkAttendanceRecordQO.setClockInSourceName(smartParkAccessControlPassRecord.getDeviceName());
        smartParkAttendanceRecordQO.setClockInWay(1);
        smartParkAttendanceRecordQO.setClockInWayName("门禁打卡");
        saveAttendanceRecord.saveAttendanceRecord(smartParkAttendanceRecordQO);
        return ResponseBodyWrapperUtil.success();
    }

    @Override
    public CommonResponseBody<List<SmartParkAccessControlPassRecordVO>> getPassRecords(SmartParkAccessControlPassRecordQO qo) {
        SmartParkAccessControlPassRecordExampleExt recordExample = new SmartParkAccessControlPassRecordExampleExt();
        SmartParkAccessControlPassRecordExampleExt.Criteria criteria = recordExample.createCriteria();
        if (qo.getTenantId() != null) {
            criteria.andTenantIdEqualTo(qo.getTenantId());
        }
        if (StringUtil.isNullOrEmpty(qo.getOrgCode())) {
            criteria.andOrgCodeEqualTo(qo.getOrgCode());
        }
        if (qo.getPassEndTime() != null) {
            criteria.andPassTimeLessThanOrEqualTo(qo.getPassEndTime());
        }
        if (qo.getPassStartTime() != null) {
            criteria.andPassTimeGreaterThanOrEqualTo(qo.getPassStartTime());
        }
        if (qo.getPassStatus() != null) {
            criteria.andPassStatusEqualTo(qo.getPassStatus());
        }
        if (StringUtils.isNotBlank(qo.getPassPersonIdNum())) {
            criteria.andPassPersonIdNumLike("%" + qo.getPassPersonIdNum() + "%");
        }
        if (StringUtils.isNotBlank(qo.getPassPersonName())) {
            criteria.andPassPersonNameLike("%" + qo.getPassPersonName() + "%");
        }
        if (StringUtils.isNotBlank(qo.getPassPersonPhoneNum())) {
            criteria.andPassPersonPhoneNumLike("%" + qo.getPassPersonPhoneNum() + "%");
        }
        if (StringUtils.isNotBlank(PassPersonType.personTypeCode(qo.getPassPersonType()))) {
            criteria.andPassPersonTypeLike("%" + PassPersonType.personTypeCode(qo.getPassPersonType()) + "%");
        }

        if (StringUtils.isNotBlank(qo.getKey())) {
            recordExample.andOrKey("%" + qo.getKey() + "%", criteria);

        }
        criteria.andIsDeletedEqualTo(0);
        if (qo.getNeedPage()) {
            recordExample.setOrderByClause("gmt_create desc limit " + (qo.getPageIndex() - 1) * qo.getPageSize() + "," + qo.getPageSize());
        } else {
            recordExample.setOrderByClause("gmt_create desc");
        }

        List<SmartParkAccessControlPassRecord> passRecords = smartParkAccessControlPassRecordMapper.selectByExample(recordExample);
        long count = smartParkAccessControlPassRecordMapper.countByExample(recordExample);

        return ResponseBodyWrapperUtil
                .successListWrapper(passRecords, count, qo, SmartParkAccessControlPassRecordVO.class);
    }
}
